<template>
  <div>
    <el-dialog v-model="dialogVisible" title="团队成员管理" width="900px" :before-close="onClose" destroy-on-close>
      <div class="members_box">
        <div class="members_box_left">
          <div class="members_search">
            <el-input v-model="searcValue" width="200" placeholder="搜索" clearable @keyup.enter="getTableData" />
          </div>
          <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="用户" name="user">
              <div class="user_box">
                <div class="left_left" v-show="activeName == 'user' && !searcValue">
                  <el-tree :data="deptDatas" :load="getDeptDatas" :props="defaultProps" :expand-on-click-node="false"
                    lazy @node-click="handleNodeClick">
                  </el-tree>
                </div>
                <div class="left_right">
                  <el-table ref="userTable" :data="userTableList" height="100%" v-loading="leftUserLoading"
                    @select="handleSelection_user" @select-all="handleSelection_userAll">
                    <el-table-column type="selection" :selectable="selectableUser" width="42" />
                    <el-table-column prop="nickName" label="昵称" width="100"> </el-table-column>
                    <el-table-column prop="deptName" label="部门" width="">
                      <template #default="scope">
                        <span v-if="scope.row.dept">
                          {{ scope.row.dept.name }}
                        </span>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="部门" name="dept">
              <div class="dept_box">
                <el-table v-loading="deptTableLoading" ref="multipleTable" :data="deptTableList" tooltip-effect="dark"
                  style="width: 100%" height="100%" :selectable="true" @select="handleSelection_dept"
                  @selection-change="handleSelectionChange_dept" @select-all="handleSelectionAll">
                  <el-table-column type="selection" width="45" :selectable="selectableDept"> </el-table-column>
                  <el-table-column prop="name" label="全选">
                    <template #header>
                      <div class="table_heder">
                        <span>全选</span>
                        <el-button type="primary" link v-if="deptSuperiorId.length"
                          @click="backSuperior">返回上一级</el-button>
                      </div>
                    </template>
                    <template #default="scope">
                      <div class="table_heder">
                        <span> <svg-icon icon-class="dept2" />{{ scope.row.deptName }}</span>
                        <el-button type="primary" link :disabled="isRowSelected(scope.row)"
                          @click="subordinateClick(scope.row)">| 下级</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="角色" name="role">
              <div class="left_left1">
                <div class="jobName" v-for="(v, i) in roleTableList" :key="i">
                  <el-checkbox :disabled="v.disabled" v-model="v.checked" @change="jobTableChange(v, 3)"
                    style="display: flex; align-items: center">
                    <p>
                      {{ v.roleName }}
                    </p>
                  </el-checkbox>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="岗位" name="job">
              <div class="left_left1">
                <div class="jobName" v-for="(v, i) in jobTableList" :key="i">
                  <el-checkbox :disabled="v.disabled" v-model="v.checked" @change="jobTableChange(v, 2)"
                    style="display: flex; align-items: center">
                    <p>
                      {{ v.postName }}
                    </p>
                  </el-checkbox>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="members_box_right">
          <p class="members_title">已选择（{{ rightAllList.length }}）</p>
          <div class="members_selected">
            <el-tag v-for="tag in rightAllList" :key="tag.id" :closable="!tag.disabled"
              :type="tag.disabled ? 'info' : 'primary'" @close="handleClose(tag)">
              {{ tag.objectName }}
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onClose">取消</el-button>
          <el-button type="primary" @click="confirmClick()"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 权限分配弹窗 -->
    <el-dialog v-model="powerVisible" title="权限分配" width="500px" custom-class="dialog_transfer_box"
      class="dialog_transfer_box">
      <el-table :data="powerList">
        <el-table-column>
          <template #header>
            <span>成员列表</span>
          </template>
          <template #default="scope">
            {{ scope.row.objectName }}
          </template>
        </el-table-column>
        <el-table-column>
          <template #default="scope">
            <div class="temp_box">
              <div class="role_box">
                <el-select v-model="scope.row.id" placeholder="请选择" class="roleType_popper_class_enterprise">
                  <el-option v-for="item in peopleRoleList" :key="item.id" :label="item.roleName" :value="item.id"
                    :disabled="item.rank == 1">
                    <div class="role_item_box">
                      <div class="name">
                        <span>{{ item.roleName }}</span>
                      </div>
                      <div class="describe">{{ item.remark }}</div>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="powerVisible = false">取消</el-button>
          <el-button type="primary" @click="addPower()"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 接口
import teamRoleApi from '@/api/teamKnowdge/teamRoleApi'
import { useTeamRoleStore } from '@/store/modules/teamRole'
import {
  apiTeamMemberQuery, apiuDeptQueryFreePerm,
  apiuUserQueryFreePerm,
  apiRoleQueryFreePerm,
  apiJobQueryFreePerm,
  apiTeamMemberAdd,
  apiTeamGetInformation
} from "@/api/teamKnowdge/teamDocApi"
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
const emits = defineEmits(['onRefresh']) //参数为数组
const teamRoleStore = useTeamRoleStore()
const route = useRoute()
const searcValue = ref<string>('')
const dialogVisible = ref<boolean>(false)
const activeName = ref<string>('user')
const peopleRoleList = ref<any>([])
const defaultRoleId = ref('')
const props = defineProps({
  treeNodeId: {
    type: Number,
    default: 0
  }
})
// 打开弹窗
const addClick = () => {
  dialogVisible.value = true
  activeName.value = 'user'
  getInit()
}
defineExpose({
  addClick
})
onMounted(() => {
  getRoleList()
})
// 获取已有成员数据
const getInit = async () => {
  let res: any = await apiTeamMemberQuery({ teamId: route.query.teamId })
  if (res.code === 200) {
    rightAllList.value = res.data.rows.map((item: any) => {
      item.disabled = true
      item.name = item.objectName
      item.typeId = item.objectId
      if (item.objectType == "0") {
        item.type = "user"
      }
      if (item.objectType == "1") {
        item.type = "dept"
      }
      if (item.objectType == "2") {
        item.type = "job"
      }
      if (item.objectType == "3") {
        item.type = "role"
      }
      return item
    })
  }
}
const getRoleList = () => {
  teamRoleApi
    .apiTeamRoleQuery({
      teamId: route.query.teamId,
      page: 0,
      size: 9999
    })
    .then((res) => {
      peopleRoleList.value = res.data.rows
      // console.log(typeof (this.peopleRoleList[0].id), 'this.peopleRoleList');
    })
    .catch((err) => {

    })
}
// 关闭弹窗
const onClose = () => {
  dialogVisible.value = false
  rightAllList.value = []
  userTableList.value = []
}
// 点击tab
const handleClick = (tab: any, event: MouseEvent) => {
  searcValue.value = ''
  if (activeName.value == tab.props.name) return
  if (tab.props.name == 'dept') {
    getDeptTableListApi(null)
  }
  if (tab.props.name == 'role') {
    apiRoleQueryUnlimited()
  }
  if (tab.props.name == 'job') {
    apiJobQueryUnlimited()
  }
}
// 搜索
const getTableData = async () => {
  if (activeName.value == 'user') {
    let params = {
      page: 0,
      size: 10000,
      nickName: searcValue.value
    }
    let res: any = await apiuUserQueryFreePerm(params)
    if (res.code === 200) {
      res.data.rows.forEach((item) => {
        item.perm = 0
        item.typeId = item.userId
      })
      userTableList.value = res.data.rows
      leftUserLoading.value = false
      rightAllList.value.map((item) => {
        if (item.type == 'user') {
          userTableList.value.forEach((res) => {
            if (item.typeId == res.userId) {
              setTimeout(() => {
                userTable.value.toggleRowSelection(res)
              })
            }
          })
        }
      })
    }
  }
  if (activeName.value == 'dept') {
    getDeptTableListApi(null)
  }
  if (activeName.value == 'role') {
    apiRoleQueryUnlimited()
  }
  if (activeName.value == 'job') {
    apiJobQueryUnlimited()
  }
}
//////////////////////////////////// //////////////////////////////////// 用户相关 start ///////////
const deptDatas = ref<any[]>([]) // 用户树数据
const userTable: any = ref() // 用户表格实例
const defaultProps = ref({ children: 'children', label: 'deptName', isLeaf: 'leaf' }) // 用户树配置
const userTableList = ref<any[]>([]) // 用户表格数据
const leftUserLoading = ref<boolean>(false) // 用户表格loading
// 获取用户数据(先获取部门)
const getDeptDatas = (node, resolve) => {
  const sort = 'id,desc'
  const params = { sort: sort }
  if (typeof node !== 'object') {
    if (node) {
      params['name'] = node
    }
  } else if (node.level !== 0) {
    params['parentId'] = node.data.deptId
  }
  setTimeout(() => {
    apiuDeptQueryFreePerm(params).then((res: any) => {
      res.data.forEach((item) => {
        item.typeId = item.deptId
        item.perm = 0
      })
      if (resolve) {
        resolve(res.data)
      } else {
        deptDatas.value = res.data
      }
    })
  }, 100)
}
// 点击树节点
const handleNodeClick = async (data) => {
  let deptId = null
  if (data.deptId === 0) {
    deptId = null
  } else {
    deptId = data.deptId
  }
  leftUserLoading.value = true
  let parmas = {
    deptId: deptId,
    size: 10000,
    page: 0,
    sort: 'id,desc'
  }
  let res: any = await apiuUserQueryFreePerm(parmas)
  if (res.code === 200) {
    res.data.rows.forEach((item) => {
      item.perm = 0
      item.typeId = item.userId
    })
    userTableList.value = res.data.rows
    leftUserLoading.value = false
    rightAllList.value.map((item) => {
      if (item.type == 'user') {
        userTableList.value.forEach((res) => {
          if (item.typeId == res.userId) {
            setTimeout(() => {
              userTable.value.toggleRowSelection(res)
            })
          }
        })
      }
    })
  }
}
// 用户表格选择
const handleSelection_user = (selectionArr: any, item: any) => {
  const checkedVal = selectionArr.find((x) => x.userId === item.userId)
  const sIndex = rightAllList.value.indexOf(item)
  let obj = {
    type: 'user', //用户0,部门1,岗位2,角色3
    typeId: item.userId,
    objectName: item.nickName,
    objectType: 0
  }
  if (checkedVal) {
    // 选中要做的事情
    toRightDataAddOrDeleteFunc(obj, 'add')
  } else {
    // 未选中要做的事情
    toRightDataAddOrDeleteFunc(obj, 'delete')
  }
} // 用户表格选择
const handleSelection_userAll = (selection: any) => {
  let a = []
  rightAllList.value.map((item) => {
    if (item.type == 'user') {
      selection.map((res) => {
        if (res.userId == item.userId || res.userId == item.typeId) {
          a.push(res)
        }
      })
    }
  })
  // 找出差异
  const differences = findDifferences(selection, a)

  if (differences.length == 0) {
    let differences = findDifferences(userTableList.value, selection)
    differences.map((item) => {
      let obj = {
        type: "user", //用户0,部门1,岗位2,角色3
        typeId: item.userId,
        objectName: item.nickName,
        objectType: 0
        // params: "query"
      }
      toRightDataAddOrDeleteFunc(obj, 'delete')
    })
  } else {
    differences.map((item) => {
      let obj = {
        type: "user", //用户0,部门1,岗位2,角色3
        typeId: item.userId,
        objectName: item.nickName,
        objectType: 0
        // params: "query"
      }
      toRightDataAddOrDeleteFunc(obj, 'add')
    })
  }
  return
} // 用户表格全选
// 用户表格禁用条件
const selectableUser = (row: any) => {
  let disabled = true
  rightAllList.value.map((item) => {
    if (item.type == 'user') {
      if (item.objectId == row.userId) {
        if (item.disabled) {
          disabled = false
        }
      }
    }
  })
  return disabled
}
const findDifferences = (arr1: any, arr2: any) => {
  // 在arr1中但不在arr2中的元素
  const differences = arr1.filter((item1) => {
    return !arr2.find((item2) => item1.typeId == item2.typeId)
  })
  return differences
}

///////////////////////////////////////////////////////////////////////// 用户相关 end ///////////

/////////////////////////////////////////// ////////// 部门相关 start ///////////
const multipleTable = ref() // 部门表格实例
const deptTableList = ref<any[]>([]) // 部门表格数据
const deptTableLoading = ref<boolean>(false) // 部门表格loading
const multipleSelection = ref<any[]>([]) // 部门表格选择
const getDeptTableListApi = async (val: any) => {
  let params: any = {
    size: 10000,
    page: 0,
    sort: 'id,desc',
    deptName: searcValue.value
  }
  if (val) {
    params.parentId = val.deptId
  }
  deptTableLoading.value = true
  let res: any = await apiuDeptQueryFreePerm(params)
  deptTableLoading.value = false
  if (res.code === 200) {
    deptTableList.value = res.data
    rightAllList.value.map((item) => {
      if (item.type == 'dept') {
        deptTableList.value.forEach((res) => {
          if (item.typeId == res.deptId) {
            setTimeout(() => {
              multipleTable.value.toggleRowSelection(res)
            })
          }
        })
      }
    })
  }
} // 获取部门表格数据
const handleSelection_dept = (selectionArr: any, item: any) => {
  const checkedVal = selectionArr.find((x) => x.deptId === item.deptId)
  let obj = {
    type: 'dept', //用户0,部门1,岗位2,角色3
    typeId: item.deptId,
    objectName: item.deptName,
    objectType: 1
  }
  if (checkedVal) {
    // 选中要做的事情
    toRightDataAddOrDeleteFunc(obj, 'add')
  } else {
    // 未选中要做的事情
    toRightDataAddOrDeleteFunc(obj, 'delete')
  }
} // 部门表格选择
const handleSelectionChange_dept = (val: any) => {
  multipleSelection.value = val
} // 部门表格全选
const handleSelectionAll = (selection: any) => {
  let a = []
  rightAllList.value.map((item) => {
    if (item.type == 'dept') {
      selection.map((res) => {
        if (res.deptId == item.id || res.typeId == item.typeId) {
          a.push(res)
        }
      })
    }
  })
  // 找出差异
  const differences = findDifferences(selection, a)
  if (differences.length == 0) {
    let differences = findDifferences(deptTableList.value, selection)
    differences.map((item) => {
      let obj = {
        type: 'dept', //用户0,部门1,岗位2,角色3
        typeId: item.deptId,
        objectName: item.deptName,
        objectType: 1
      }
      toRightDataAddOrDeleteFunc(obj, 'delete')
    })
  } else {
    differences.map((item) => {
      let obj = {
        type: 'dept', //用户0,部门1,岗位2,角色3
        typeId: item.deptId,
        objectName: item.deptName,
        objectType: 1
      }
      toRightDataAddOrDeleteFunc(obj, 'add')
    })
  }
  return
} // 部门表格全选
const selectableDept = (row: any, index: number) => {
  let disabled = true
  rightAllList.value.map((item) => {
    if (item.type == 'dept') {
      if (item.objectId == row.deptId) {
        if (item.disabled) {
          disabled = false
        }
      }
    }
  })
  return disabled
} // 部门表格选择条件
const deptSuperiorId = ref<any[]>([]) // 部门上级id
const backSuperior = () => {
  // 返回上一级
  getDeptTableListApi(deptSuperiorId.value[deptSuperiorId.value.length - 1])
  deptSuperiorId.value.pop()
}
const isRowSelected = (row: any) => {
  return multipleSelection.value.includes(row)
} // 判断是否选中
const subordinateClick = (val: any) => {
  // 下级点击
  deptSuperiorId.value.push({ id: val.deptId })
  getDeptTableListApi(val)
}
/////////////////////////////////////////////////////////////////// 部门相关 end ///////////

////////// //////////////////////////////////////////////////////// 角色相关 start ///////////
const roleTableList = ref<any[]>([]) // 角色表格数据
const apiRoleQueryUnlimited = async () => {
  // 获取角色数据
  let res: any = await apiRoleQueryFreePerm({ roleName: searcValue.value })
  if (res.code === 200) {
    res.data.forEach((item: any) => {
      item.checked = false
    })
    rightAllList.value.map((item) => {
      if (item.type == 'role' || item.objectType == 3) {
        res.data.map((res: any) => {
          if (res.roleId == item.typeId) {
            res.checked = true
            res.disabled = item.disabled
          }
        })
      }
    })
    roleTableList.value = res.data
  }
}
const jobTableChange = (row: any, type: any) => {
  let obj = {
    objectType: type, //用户0,部门1,岗位2,角色3
    typeId: type == 3 ? row.roleId : row.postId,
    objectName: type == 3 ? row.roleName : row.postName,
  }
  if (row.checked) {
    toRightDataAddOrDeleteFunc(obj, 'add')
  } else {
    toRightDataAddOrDeleteFunc(obj, 'delete')
  }
}
////////////////////////////////////////////////////////// 角色相关 end ///////////

/////////////////////////////////////////////////////// 岗位相关 start ///////////
const jobTableList = ref<any[]>([]) // 岗位表格数据
const apiJobQueryUnlimited = async () => {
  // 获取岗位数据
  let res: any = await apiJobQueryFreePerm({ postName: searcValue.value })
  if (res.code === 200) {
    res.data.forEach((item: any) => {
      item.checked = false
    })
    rightAllList.value.map((item) => {
      if (item.type == 'job' || item.objectType == 2) {
        res.data.map((res: any) => {
          if (res.postId == item.typeId) {
            res.checked = true
            res.disabled = item.disabled
          }
        })
      }
    })
    jobTableList.value = res.data
  }
}
/////////////////////// 岗位相关 end ///////////

////////////////////////////////// 已选择 start ///////////
const rightAllList = ref<any[]>([]) // 已选择数据
// 向右添加和取消方法
const toRightDataAddOrDeleteFunc = (obj: any, type: any) => {
  if (type == 'add') {
    rightAllList.value.push(obj)
  } else {
    rightAllList.value.forEach((item, index) => {
      if (item.type == obj.type && item.typeId == obj.typeId) {
        rightAllList.value.splice(index, 1)
      }
    })
  }
}
// 右侧标签删除操作
const handleClose = (obj: any) => {
  rightAllList.value.forEach((item, index) => {
    if (item.type == obj.type && item.typeId == obj.typeId) {
      rightAllList.value.splice(index, 1)
    }
  })
  if (obj.type == 'user') {
    userTableList.value.map((item) => {
      if (item.userId == obj.typeId) {
        userTable.value.toggleRowSelection(item)
      }
    })
  }
  if (obj.type == 'dept') {
    deptTableList.value.map((item) => {
      if (item.deptId == obj.typeId) {
        multipleTable.value.toggleRowSelection(item)
      }
    })
  }
  if (obj.type == 'role') {
    roleTableList.value.map((item) => {
      if (item.roleId == obj.typeId) {
        item.checked = false
      }
    })
  }
  if (obj.type == 'job') {
    jobTableList.value.map((item) => {
      if (item.postId == obj.typeId) {
        item.checked = false
      }
    })
  }
}
//////////////////////////////////////////////////// 权限分配 start ///////////
import roleList_team from '@/utils/roleList'

const roleList = reactive(roleList_team.roleList_team) // 权限筛选列表

const powerVisible = ref<boolean>(false) // 权限分配弹窗
const powerList = ref<any[]>([]) // 权限分配列表
// 打开分配权限弹窗
const confirmClick = async () => {// 获取默认角色
  let res1 = await apiTeamGetInformation({
    id: route.query.teamId
  })
  if (res1.code == 200) {
    defaultRoleId.value = res1.data.defaultRole
  }
  let res = rightAllList.value.filter((item) => !item.disabled)
  if (res.length != 0 && rightAllList.value.length != 0) {
    powerVisible.value = true
    powerList.value = res
    powerList.value.map((item) => {
      if (defaultRoleId.value) {
        item.id = Number(defaultRoleId.value)
      } else {
        item.id = null
      }
    })
  } else {
    ElMessage.warning('请选择左侧人员')
  }
}
// 分配权限接口
const addPower = async () => {
  const isValid = powerList.value.every((item) => item.id)
  if (!isValid) {
    ElMessage.warning('请选择权限')
    return
  }
  let teamArr = powerList.value.map((item) => {
    return {
      teamId: route.query.teamId,
      objectId: item.typeId,
      roleId: item.id,
      objectType: item.objectType
    }
  })
  const res = await apiTeamMemberAdd(teamArr)
  if (res.code == 200) {
    ElMessage.success('分配成功')
    powerVisible.value = false
    onClose()
    emits('onRefresh')
  }

}
/////////////////////////////////////////////////////// 权限分配 end ///////////
</script>
<style scoped>
.el-select-dropdown__item {
  width: 270px;
  height: auto;
  line-height: 20px;
  /* color: #1f2329 !important; */
  padding-bottom: 5px;
  padding-top: 5px;
  white-space: normal !important;
  word-wrap: break-word !important;

  .name {
    font-size: 14px;
    font-weight: 700;
  }

  .describe {
    font-size: 12px;
    color: #999;
  }
}
</style>
<style scoped lang='scss'>
:deep(.el-dialog__header) {
  padding: 0 !important;
  padding-bottom: 10px !important;
}

:deep(.el-dialog__body) {
  padding: 0 !important;
  height: 600px !important;

  .el-tabs {
    height: calc(100% - 52px) !important;
    display: flex;
    flex-direction: column;

    .el-tabs__content {
      flex: 1;

      .el-tab-pane {
        height: 100%;
      }
    }
  }
}

:deep(.dialog_transfer_box) {
  .el-dialog__body {
    height: 400px !important;
  }
}

.members_box {
  height: 100%;
  display: flex;

  .members_box_left {
    width: 60%;
    border-right: 1px solid #e6e6e6;

    .members_search {
      padding: 10px 0px;
      padding-right: 20px;
    }
  }

  .members_box_right {
    width: 40%;
  }
}

.user_box {
  height: 100%;
  display: flex;

  .left_left {
    width: 40%;
    height: 100%;
    overflow: auto;
    border-right: 1px solid #e6e6e6;
  }

  .left_right {
    flex: 1;
    width: 60%;
    height: 100%;
  }
}

.dept_box {
  height: 100%;

  .table_heder {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.members_box_right {
  padding: 10px;
  padding-top: 0;

  .members_title {
    font-size: 16px;
    color: #333;
  }

  .members_selected {
    display: flex;
    margin-top: 10px;
    flex-wrap: wrap;
    gap: 10px;
    font-weight: 700;
  }
}

:deep(.dialog_transfer_box) {
  .el-dialog__body {
    height: 400px;

    .el-table {
      height: 100%;
    }
  }
}

.role_box {
  width: 100%;

  :deep(.el-input__inner) {
    width: 100px;
    border: 0;
  }

  .all_role_text {
    margin-left: 15px;
    color: #bbbfc4;
    font-size: 13px;
  }
}

.role_item_box {
  padding: 10px 0;

  .name {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
  }

  .describe {
    font-size: 11px;
  }
}

.el-select-dropdown__item {
  height: auto;

  p {
    margin: 0;
  }

  line-height: 20px;
}
</style>